# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
from gettext import gettext as _
 
import gnomevfs
from deskbar.Handler import Handler
from deskbar.Match import Match
import glob, re, os
import deskbar
#import gtk, gtk.gdk
 
HANDLERS = {
        "DoodleSearchHandler" : {
                "name": _("Doodle Search"),
                "description": _("Search your files using doodle"),
        }
}
 
class DoodleSearchMatch(Match):
        def __init__(self, backend, **args):
                deskbar.Match.Match.__init__(self, backend, **args)
                self.url = args['url']
		self.name = args['name']
 
        def action(self, text=None):
                gnomevfs.url_show(self.url)

	def get_category(self):
		return "doodle"
 
        def get_verb(self):
                return _("File: <b>%(name)s</b>")
 
        def get_hash(self, text=None):
                return self.url
 
 
class DoodleSearchHandler(Handler):
        def __init__(self):
                deskbar.Handler.Handler.__init__(self, "")
 
        def query(self, query):
                result = []
                query = query.lower()
		f = os.popen("doodle %s"%query)
		lines = f.readlines()
		f.close()
		if len(lines) == 2 and lines[1] == '\tNot found!\n':
			return []
		else:
			if len(lines) < 10:
				max = len(lines)
			else:
				max = 10
			for l in lines[1:max]:
				l = l.strip()
				_l = l.split('/')
				result.append(DoodleSearchMatch(self, name=_l[len(_l)-1], url='file://'+l))
                return result

